package com.link.gateway.core.comproperty;

import com.link.gateway.base.enterprise.model.Enterprise;
import com.link.gateway.base.urlinfo.model.UrlInfo;
import com.link.gateway.base.urlinfo.service.UrlInfoService;
import com.link.gateway.base.user.model.User;
import com.link.gateway.core.utils.SpringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;

/**
 * 运行中的变量
 *
 * @author huanglongjian
 * @date 2019-07-23 14:02
 */

public class RunProperties {
    private static final Logger logger = LogManager.getLogger(RunProperties.class);

    /**
     * 当前线程的用户信息
     */
    public static final ThreadLocal<User> TEMP_USER = new ThreadLocal();

    /**
     * 当前线程的企业信息
     */
    public static final ThreadLocal<Enterprise> TEMP_ENTERPRISE = new ThreadLocal();

    /**
     * 当前线程的token
     */
    public static final ThreadLocal<String> TOKEN = new ThreadLocal();

    /**
     * 当前线程的token
     */
    public static final ThreadLocal<String> CURRENT_CLIENT_ID = new ThreadLocal();

    /**
     * 当前请求对应的范围
     */
    public static final ThreadLocal<String> SCOPE = new ThreadLocal();


    /**
     * 默认安全模式的url
     */
    private static Map<String, String> defUrl;

    /**
     * 所有的url 范围
     */
    private static Map<String, String> allUrlScope;

    /**
     * 存放当前所有url的详细信息
     */
    private static Map<String, UrlInfo> allUrlDetail;

    public static Map<String, String> getDefUrl() {
        refreshCurUrlMsg();
        return defUrl;
    }

    public static void setDefUrl(Map<String, String> defUrl) {
        RunProperties.defUrl = defUrl;
    }

    public static Map<String, String> getAllUrlScope() {
        refreshCurUrlMsg();
        return allUrlScope;
    }

    public static void setAllUrlScope(Map<String, String> allUrlScope) {
        RunProperties.allUrlScope = allUrlScope;
    }

    public static Map<String, UrlInfo> getAllUrlDetail() {
        refreshCurUrlMsg();
        return allUrlDetail;
    }

    public static void setAllUrlDetail(Map<String, UrlInfo> allUrlDetail) {
        RunProperties.allUrlDetail = allUrlDetail;
    }

    /**
     * 获取这些值之前，先校验版本号是否和redis里面统一，不统一则获取新的
     *
     * @author huanglongjian
     * @date 2019-07-25 12:51
     */
    private static void refreshCurUrlMsg() {
        UrlInfoService urlInfoService = SpringUtils.getBean(UrlInfoService.class);
        try {
            //重新获取新的信息
            urlInfoService.setDefUrlCache();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
